package com.demo

import java.net.{Authenticator, PasswordAuthentication}
import scala.xml.{Elem, XML}
import scalax.io.InputStreamResource

/** Twitter API Client
 *  Exposes methods to talk to the RESTful Twitter API client.
 *
 *  @author Jorge Ortiz
 *  @version 0.1
 */
object Twitter {
  /** Verify Twitter credentials
   *  Sets the default java.net.Authenticator to use those credentials
   *  for future requests.
   *
   *  @param username the username
   *  @param password the password
   *  @returns true if the credentials are valid, false otherwise
   */
  def verifyCredentials(username: String, password: String): Boolean = {
    Authenticator.setDefault(new Authenticator {
      override protected def getPasswordAuthentication =
        new PasswordAuthentication(username, password.toCharArray)
    })
    
    call("account/verify_credentials").
      map(n => n.label == "authorized" && n.text == "true").
      getOrElse(false)
  }
  
  /** Get the the last twenty status updates of the logged-in user's friends
   *
   *  @returns Some(xml) if the request is succesful, None otherwise
   */
  def friendsTimeline =
    call("statuses/friends_timeline").
      map(xml => (xml \ "status").toList).
      getOrElse(List())
  
  /** Make a call on the Twitter API.
   *
   *  @param method the method to be called
   *  @returns Some(xml.Elem) if the request was sucesfful, None otherwise
   */
  def call(method: String): Option[Elem] = {
    try {
      Some(
        InputStreamResource.url("http://twitter.com/" + method + ".xml").
          map(XML.load))
    } catch {
      case e: java.io.IOException => None
      case e: Exception => e.printStackTrace; None
    }
  }
}
